package com.industrial.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.druid.util.StringUtils;
import com.industrial.common.core.constant.SdAuthenticationApi;
import com.industrial.common.log.annotation.Log;
import com.industrial.system.api.domain.BizAccountMapping;
import com.industrial.system.api.domain.SysUser;
import com.industrial.system.api.model.LoginUser;
import com.industrial.system.mapper.BizAccountMappingMapper;
import com.industrial.system.mapper.SysUserMapper;
import com.industrial.system.service.IBizAccountMappingService;
import com.industrial.system.service.ISysPermissionService;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class BizAccountMappingServiceImpl implements IBizAccountMappingService {

    private static final Logger log = LoggerFactory.getLogger(BizAccountMappingServiceImpl.class);


    private BizAccountMappingMapper bizAccountMappingMapper;

    private SysUserMapper sysUserMapper;

    private final CloseableHttpClient closeableHttpClient;

    public BizAccountMappingServiceImpl(BizAccountMappingMapper bizAccountMappingMapper,SysUserMapper sysUserMapper,CloseableHttpClient closeableHttpClient) {
        this.bizAccountMappingMapper = bizAccountMappingMapper;
        this.sysUserMapper = sysUserMapper;
        this.closeableHttpClient = closeableHttpClient;
    }

    @Autowired
    private ISysPermissionService permissionService;

    /**
     * 通过省用户ID查询用户信息     注：此方法没用，懒得删
     * <p>
     *     如果没有查询到用户数据<br>
     *     就是用户与省用户关系表中新增一条数据<br>
     *     如果查询到数据则反回该用户信息
     * </p>
     * @param userInfoMap 省用户信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LoginUser selectUserMappingInfoByZwfwuuid(Map<String,Object> userInfoMap) {
        String zwfwUuid = (String)userInfoMap.get("zwfwUuid");
        String userName = (String)userInfoMap.get("username");
        String userType = (String)userInfoMap.get("usertype");
        String userId = (String)userInfoMap.get("id");
        BizAccountMapping mappingUserInfo = bizAccountMappingMapper.selectUserMappingInfoByZwfwuuid(zwfwUuid,"");

        LoginUser loginUser = null;
        if(mappingUserInfo == null){

            //如果用户Id等于2，代表该用户是法人用户，需要调用接口获取该企业的统一社会信用代码
            if(StringUtils.equals(userType,"2")){
                HttpGet httpGet = new HttpGet(String.format(SdAuthenticationApi.GET_CORUSER_BY_TOKEN));
                httpGet.setHeader("Authorization","Bearer " + userId);
                try(CloseableHttpResponse response = closeableHttpClient.execute(httpGet)){
                    int statusCode = response.getStatusLine().getStatusCode();
                    String responseStr = EntityUtils.toString(response.getEntity());
                    if(statusCode == 200){
                        log.error("获取到的法人信息：{}",responseStr);
                    }else{
                        log.error("获取失败：{}",responseStr);
                    }
                } catch (Exception e) {
                    log.error("获取法人信息失败:{}",e.toString());
                    return loginUser;
                }
            }

            //查询原业务库中的用户数据
            SysUser sysUser = sysUserMapper.selectUserByUserName(userName);
            if(sysUser != null){
                loginUser = new LoginUser();
                //如果mappingUserInfo是空，则需要在关系表中插入映射关系
                BizAccountMapping insertParams = new BizAccountMapping();
                insertParams.setId(IdUtil.simpleUUID());
                insertParams.setsPtUserId(zwfwUuid);
                insertParams.setBizUserId(sysUser.getUserId());
                insertParams.setBizUserName(sysUser.getUserName());
                insertParams.setBizUserPwd(sysUser.getPassword());
                insertParams.setBaseCreateTime(new Date());

                //判断该用户名或省用户Id是否已存在
                int count = bizAccountMappingMapper.selectUserExisted(userName,zwfwUuid);
                if(count > 0){
                    throw new RuntimeException("数据错误，该用户的省Id或者是用户名称已在业务库中存在");
                }
                bizAccountMappingMapper.insert(insertParams);
                loginUser.setSysUser(sysUser);

                // 角色集合
                Set<String> roles = permissionService.getRolePermission(sysUser);
                // 权限集合
                Set<String> permissions = permissionService.getMenuPermission(sysUser);

                loginUser.setRoles(roles);
                loginUser.setPermissions(permissions);
            }
        }else{
            loginUser = new LoginUser();
            SysUser sysUser = sysUserMapper.selectUserById(mappingUserInfo.getBizUserId());
            loginUser.setSysUser(sysUser);
            // 角色集合
            Set<String> roles = permissionService.getRolePermission(sysUser);
            // 权限集合
            Set<String> permissions = permissionService.getMenuPermission(sysUser);
            loginUser.setRoles(roles);
            loginUser.setPermissions(permissions);
        }
        return loginUser;
    }

    /**
     * 通过省用户ID查询业务用户信息
     *
     * @param uuid
     * @return
     */
    @Override
    public BizAccountMapping selectUserInfoBySptUuid(String uuid,String uscc) throws RuntimeException {
        BizAccountMapping mappingUserInfo = bizAccountMappingMapper.selectUserMappingInfoByZwfwuuid(uuid,uscc);
        if(mappingUserInfo != null){
            return mappingUserInfo;
        }

        int count =  bizAccountMappingMapper.selectUserUuidMappingCount(uscc);

        if(count > 0){
            throw new RuntimeException(String.format("%s企业已绑定其它省级用户",uscc));
        }

        //查询原业务库中的用户数据
        SysUser sysUser = sysUserMapper.selectUserByUserName(uscc);
        if(sysUser == null){
            throw new RuntimeException("当前用户没有业务数据库中存在");
        }

        BizAccountMapping insertParams = new BizAccountMapping();
        insertParams.setId(IdUtil.simpleUUID());
        insertParams.setsPtUserId(uuid);
        insertParams.setBizUserId(sysUser.getUserId());
        insertParams.setBizUserName(sysUser.getUserName());
        insertParams.setBizUserPwd(sysUser.getPassword());
        insertParams.setBaseCreateTime(new Date());
        bizAccountMappingMapper.insert(insertParams);
        return insertParams;
    }

    /**
     * 查询山东通用户和业务用户的绑定状态
     *
     * @param userId 山东通平台Id
     */
    @Override
    public LoginUser selectUserInfoBySptId(String userId) {
        LoginUser loginUser = null;
        try{

            BizAccountMapping accountMapping = bizAccountMappingMapper.selectUserBindInfo(userId);
            if(accountMapping == null){
                return loginUser;
            }
            loginUser = new LoginUser();
            SysUser sysUser = sysUserMapper.selectUserById(accountMapping.getBizUserId());
            loginUser.setSysUser(sysUser);
            // 角色集合
            Set<String> roles = permissionService.getRolePermission(sysUser);
            // 权限集合
            Set<String> permissions = permissionService.getMenuPermission(sysUser);
            loginUser.setRoles(roles);
            loginUser.setPermissions(permissions);
            return loginUser;
        }catch (Exception e){
            e.printStackTrace();
            return loginUser;
        }
    }

    @Override
    public void insert(BizAccountMapping bizAccountMapping) {
        bizAccountMappingMapper.insert(bizAccountMapping);
    }

    @Override
    public BizAccountMapping selectUserBindBySptId(String sPtUserId) {
       return bizAccountMappingMapper.selectUserBindInfo(sPtUserId);
    }
}
